const db = wx.cloud.database()
const app = getApp();
const _ = db.command;
Page({
  data: {
    nickName: '',
    passWord: '',
    radio: 0,
    loginLoading: false,
  },
  onChangeNickName: function (e) {
    this.setData({
      nickName: e.detail
    })
  },
  onChangeRadio(e) {
    this.setData({
      radio: e.detail
    })
  },
  onChangePassWord: function (e) {
    this.setData({
      passWord: e.detail
    })
  },
  navigatorRegister(e) {
    wx.redirectTo({
      url: '/pages/login/index',
    });
  },
  onShow() {
    wx.hideHomeButton({
      success: function () {
        // console.log(1);
      },
      fail: function () {
        // console.log(2);
      },
      complete: function () {
        // console.log(3);
      }
    });
  },
  // 登录按钮
  onSubmit: function (e) {
    const that = this;
    this.setData({
      loginLoading: true,
    })
    if (this.data.nickName == '') {
      wx.showToast({
        title: '请输入账号！',
        icon: 'none'
      })
      return
    }
    if (this.data.passWord == '') {
      wx.showToast({
        title: '请输入密码！',
        icon: 'none'
      })
      return
    }
    // 开始使用云开发数据库
    const {
      nickName,
      passWord,
      radio
    } = this.data;
    db.collection('Management_user').where({
      nickName: _.eq(nickName),
    }).get().then(res => {
      console.log(res)
      if (res.data.length === 1) {
        wx.showToast({
          title: '用户已存在！',
          icon: 'error'
        });
        that.setData({
          nickName: '',
          passWord: ''
        });
      } else {
        db.collection('Management_user').add({
          data: {
            nickName: nickName,
            passWord: passWord,
            type: radio,
            questions: [],
            selectAdmin: "",
            selectAnswer: [],
            selects: [],
            userList: []
          }
        }).then(res => {
          if (res._id !== '') {
            wx.showToast({
              title: '注册成功',
              icon: 'success',
              duration: 1500,
            }).then(() => {
              wx.redirectTo({
                url: '/pages/index/index'
              });
            })
          } else {
            wx.showToast({
              title: '注册失败！',
              icon: 'error'
            })
          }
        })
        this.setData({
          loginLoading: false,
        })
      }
    })
  }
})